<template>
  <FormItem v-bind="formItemProps" :rules="computeRules" :disabled="inputDisabled">
    <template #default>
      <ElDatePicker
        style="width: 100%"
        :picker-options="pickerOption"
        :value="innerVal"
        v-bind="inputProps"
        :placeholder="computePlaceholder"
        :type="type"
        :disabled="inputDisabled"
        v-on="listeners"
        @input="emitInput" />
      <div v-if="$slots.warn" class="el-form-item__warn">
        <slot name="warn"></slot>
      </div>
    </template>
    <template #error="{ error }">
      <div v-if="$scopedSlots.error && $scopedSlots.error(error)" class="el-form-item__error">
        <slot name="error" :error="error">{{ error }}</slot>
      </div>
    </template>
    <template #label>
      <slot name="label"></slot>
    </template>
  </FormItem>
</template>

<script>
  import formInput from './form-input'
  import formPick from '@/components/form/form-pick'
  import { toDate } from '@web-utils/integrations/dayjs'
  import { filterProperties, normalizeProps } from '@/util'

  const autoBindKeys = [
    'type',
    'timeArrowControl',
    'size',
    'format',
    'valueFormat',
    'readonly',
    'placeholder',
    'startPlaceholder',
    'endPlaceholder',
    'prefixIcon',
    'clearIcon',
    'name',
    'disabled',
    'clearable',
    'id',
    'popperClass',
    'editable',
    'align',
    'value',
    'defaultValue',
    'defaultTime',
    'rangeSeparator',
    'pickerOptions',
    'unlinkPanels',
    'validateEvent'
  ].filter(key => !['value', 'placeholder', 'disabled', 'type', 'pickerOptions'].includes(key))

  export default {
    name: 'FormDatePicker',
    mixins: [formInput, formPick],
    props: {
      format: String,
      valueFormat: String,
      rangeSeparator: String,
      startPlaceholder: String,
      endPlaceholder: String,
      start: String,
      end: String,
      year: Boolean,
      month: Boolean,
      dates: Boolean,
      week: Boolean,
      dateTime: Boolean,
      dateTimeRange: Boolean,
      dateRange: Boolean,
      monthRange: Boolean,
      miniDate: String,
      maxDate: String,
      pickerOptions: Object,
      split: {
        type: Boolean,
        default: true
      }
    },
    computed: {
      prefix() {
        return '请选择'
      },
      mini() {
        if (this.miniDate) {
          const date = toDate(this.miniDate)
          date.setDate(date.getDate() - 1)
          return date
        } else {
          return null
        }
      },
      max() {
        if (this.maxDate) {
          return toDate(this.maxDate)
        } else {
          return null
        }
      },
      pickerOption() {
        return {
          disabledDate: time => {
            if (!this.mini && !this.max) {
              return false
            }
            const currentTime = time.getTime()
            if (this.mini && !this.max) {
              return currentTime <= this.mini.getTime()
            } else if (!this.mini && this.max) {
              return currentTime >= this.max.getTime()
            } else if (this.mini && this.max) {
              // return currentTime <= this.mini.getTime() && currentTime >= this.max.getTime()
              return !(currentTime > this.mini.getTime() && currentTime <= this.max.getTime())
            } else {
              return false
            }
          },
          ...this.pickerOptions
        }
      },
      innerVal() {
        if (this.range && this.split) {
          const val = []
          val.push(this.start || '')
          val.push(this.end || '')
          return val
        } else {
          return this.value
        }
      },
      fat() {
        if (this.year) {
          return 'yyyy'
        } else if (this.month || this.monthRange) {
          return 'yyyy-MM'
        } else if (this.week) {
          return 'yyyy 第 WW 周'
        } else if (this.dateTime || this.dateTimeRange) {
          return 'yyyy-MM-dd HH:mm:ss'
        } else {
          return 'yyyy-MM-dd'
        }
      },
      inputProps() {
        return filterProperties(
          {
            ...normalizeProps(this.$attrs),
            ...this.$props,
            valueFormat: this.week ? 'yyyy-MM-dd' : this.valueFormat || this.fat,
            format: this.format || this.fat,
            rangeSeparator: this.rangeSeparator || '至',
            startPlaceholder: this.startPlaceholder || '开始日期',
            endPlaceholder: this.endPlaceholder || '结束日期'
          },
          autoBindKeys
        )
      },
      range() {
        return this.dateTimeRange || this.dateRange || this.monthRange
      },
      type() {
        if (this.year) {
          return 'year'
        } else if (this.month) {
          return 'month'
        } else if (this.dates) {
          return 'dates'
        } else if (this.week) {
          return 'week'
        } else if (this.dateTime) {
          return 'datetime'
        } else if (this.dateTimeRange) {
          return 'datetimerange'
        } else if (this.dateRange) {
          return 'daterange'
        } else if (this.monthRange) {
          return 'monthrange'
        } else {
          return 'date'
        }
      }
    },
    methods: {
      emitInput(val) {
        if (this.range && this.split) {
          if (val) {
            this.$emit('update:start', val[0])
            this.$emit('update:end', val[1])
          } else {
            this.$emit('update:start', null)
            this.$emit('update:end', null)
          }
        } else {
          this.$emit('input', val)
        }
      }
    }
  }
</script>
